package com.ml.controller;

import com.ml.commonutils.RandomUtil;
import com.ml.commonutils.Result;
import com.ml.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.runtime.Log;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author ShuHaoNan
 * @email shuhaonan1@gmail.com
 * @date 2020/10/26 12:45
 */
@RestController
@RequestMapping("/msm")
@Api(tags = "阿里云短信服务")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param phone 手机号
     * @return
     */
    @ApiOperation("发送验证码")
    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable("phone") String phone) {
        // 随机生成四位数验证码
        String code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(param, phone);
        // 判断是否发送成功，如果发送成功，把验证码存入Redis中
        if (isSend) {
            // 验证码放入Redis中，key：手机号  value：验证码  存放 5分支
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok().data("code", code);
        }
        return Result.error().message("短信发送失败");
    }

    /**
     * 根据手机号从Redis中获取验证码
     */
    @ApiOperation("获取验证码")
    @GetMapping("/getCode/{phone}")
    public Result getCode(@PathVariable("phone") String phone) {
        String code = msmService.getCode(phone);
        return Result.ok().data("code", code);
    }

}
